package com.starter.home.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.starter.home.domain.entity.User;
import com.starter.home.domain.vo.FileVo;
import com.starter.home.service.IUserService;
import com.starter.home.util.ExcelUtils;
import com.starter.home.util.MD5Util;
import com.starter.home.util.MyUtil;
import com.starter.home.util.ResponseResult;
import com.starter.home.util.constant.MessageConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * @author jian.li
 * @date 2020年 05月01日 15:59:37
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileContrller {

    @Value("${file.fileUploadPath}")
    private String fileUploadPath;
    @Autowired
    private IUserService userService;


    @PostMapping(value = "/upload")
    public ResponseResult imgUpload(HttpServletRequest req, MultipartHttpServletRequest multiReq, HttpSession session)
            throws IOException {
        Optional<User> user = MyUtil.getUser(session);
        if (!user.isPresent()){
            return ResponseResult.error(MessageConstant.SESSION_OUTTIME);
        }
        int id = user.get().getId();
        //我这里用的springboot 在application.properties中配置，使用@Value 获取的文件上传目录
        log.info("---" + fileUploadPath);
        MultipartFile file = multiReq.getFile("file");
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        String localFileName = MD5Util.md5(file.getInputStream()) + suffix;
        File localFile = new File(fileUploadPath + localFileName);
        if (!localFile.exists()) {
            localFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(
                    localFile);
            List<MultipartFile> file1 = multiReq.getMultiFileMap().get("file");
            FileInputStream fs = null;
            for (MultipartFile multipartFile : file1) {
                fs = (FileInputStream) multipartFile.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fs.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
            }
            fos.close();
            fs.close();
        }
        Boolean aBoolean = userService.saveUser(id, "http://localhost:8080/img/" + localFileName);
        if (aBoolean){
            return ResponseResult.success("http://localhost:8080/img/" + localFileName);
        }else {
            return ResponseResult.error("");
        }

    }
    @PostMapping(value = "/uploadFile")
    public ResponseResult uploadFile(HttpServletRequest req, MultipartHttpServletRequest multiReq, HttpSession session)
            throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(2);
        // params.setTitleRows(0);
        List<User> users = ExcelUtils.importExcel(multiReq.getMultiFileMap().get("file").get(0).getInputStream(), 1, 1, User.class);
        if (users.size() > 0){

            int res = userService.saveList(users);
            if (res > 0){
                return ResponseResult.success(String.format("成功导入%s条。",res));
            }else{
                return ResponseResult.error("导入失败");
            }
        }else{
            return ResponseResult.error("文件为空");
        }

    }

}
